// hex表示方式转rgb表示方式，str以字符串还是数组返回
/** hex转换rgb */
export function hexToRgb(sColor: string, str = true) {
    const reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-f]{6})$/
    sColor = String(sColor).toLowerCase()
    if (sColor && reg.test(sColor)) {
        if (sColor.length == 4) {
            // 三位颜色
            let sColorNew = '#'
            for (let i = 1; i < 4; i++) {
                //字符串contact字符串等同于+
                sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
            }
            sColor = sColorNew
        }
        const sColorChange = []
        for (let i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt(`0x${sColor.slice(i, i + 2)}`))
        }
        if (!str) {
            return sColorChange
        }
        return `rgb(${sColorChange.join(',')})`
    }
    if (/^(rgb|RGB)/.test(sColor)) {
        if (str) return sColor
        const arr = sColor.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
        return arr.map((i) => Number(i))
    }
}

/**
 * 初始化html2canvas
 * @returns 
 */
export const initHtml2Canvas = () => {
    return window.html2canvas
        ? Promise.resolve(window.html2canvas)
        : import('html2canvas').then((res) => res.default)
}

/**
 * 将卡片html字符串转为base64图片
 * @param cardHtmlStr 卡片html字符串
 * @param option 选项
 * @returns 
 */
export interface DrawCardToBase64Option {
    draw?: boolean, // 是否绘制
    wrap?: HTMLElement, // 绘制容器
    className?: string, // 卡片类名
    [p: string]: any
}
export const drawCardToBase64 = (
    cardHtmlStr: string,
    option?: DrawCardToBase64Option) => {
    const _option = option || {}
    const _cardWrap = document.createElement('div')
    _cardWrap.className = _option.className || ''
    _cardWrap.innerHTML = cardHtmlStr
    return new Promise<{ dom: HTMLElement, base64?: string }>((resolve, reject) => {
        if (_option.draw && _option.wrap) {
            _option.wrap.appendChild(_cardWrap)
            // 引入 html2canvas 生成图片
            return initHtml2Canvas().then((r) => {
                r(_cardWrap, {
                    scale: 4,
                    letterRendering: 1,
                    allowTaint: !0,
                    useCORS: !0,
                    scrollY: -window.scrollY,
                })
                    .then((r: HTMLCanvasElement) => {
                        const o = r.toDataURL('base64')
                        resolve({ base64: o, dom: _cardWrap })
                    })
                    .catch((err: any) => {
                        reject(err)
                    })
            })
        } else {
            resolve({ dom: _cardWrap })
        }
    })
}


// 将时间戳转为日期格式，e为true时，返回年月日，否则返回月日
export const timestampToDate = (t: number, e: boolean) => {
    const n = new Date(t)
    if (e) {
        const r = `${n.getMonth() + 1}月${n.getDate()}日`
        return n.getFullYear() !== new Date().getFullYear()
            ? `${n.getFullYear()}年${r}`
            : r
    }
    return `${n.getMonth() + 1}月${n.getDate()}日`
}

// 去除url中的http:
export const clearUrlHttp = (t: string) => {
    return t ? t.replace(/^http:/, '') : ''
}
// 将url转为webp格式
export const handleImageUrlToWebp = (
    url: string, // 图片url
    e: number, // 宽度
    n: number = 0, // 高度
    r: number = 0, // 旋转角度?
    o: number = 0 // 是否旋转?
) => {
    if (
        ((e = Math.abs(Math.round(e))),
            (n = Math.abs(Math.round(n))),
            e > 4096 || n > 4096)
    )
        return url
    if (!url) return url
    let urlList = url.split('@')
    let imageMatch = (url = urlList && urlList[0]).match(
        /(.*\.(jpg|jpeg|gif|png))(\?.*)?/
    )
    if (!imageMatch) return url
    if (!(-1 !== url.indexOf('/bfs/'))) return url
    let c = r && o ? '_' + r + 'e_' + o + 'c' : ''
    let u = e || n ? `@${e ? `${e}w` : ''}${n ? `_${n}h` : ''}${c}` : ''
    let s = imageMatch[3] ? imageMatch[3] : ''
    return `${imageMatch[1]}${u ? u + '_' : '@'}${s}.webp`
}

// 将html字符串转为安全的html转义字符
export const replaceHtmlToSafeStr = (t: string) => {
    return (t = t.toString())
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&#34;')
        .replace(/'/g, '&#39;')
        .replace(/\n/g, '')
}

export const setAttribute = (dom: HTMLElement, attr: string, value: string) => {
    dom?.setAttribute?.(attr, value)
}

// 将秒数转为时间格式
export const secondsToTime = (t: number | string) => {
    if (typeof t === 'string' && t.indexOf(':') !== -1) {
        return t
    } else if (typeof t === 'number') {
        let minutes, seconds
        if (t / 60 < 1) {
            minutes = 0
            seconds = t
        } else {
            minutes = Math.floor(t / 60)
            seconds = t - 60 * minutes
        }
        return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
}


// 将数字转为万或亿或--
export const changeNumberToWanYi = (t: number | string | boolean) => {
    return isNaN(parseInt(t.toString())) || parseInt(t.toString()) < 0 || null == t ? "--" : -1 !== String(t).indexOf(".") || -1 !== String(t).indexOf("-") ? t : 0 === parseInt(t.toString()) ? 0 : (t = parseInt(t.toString())) >= 1e4 && t < 1e8 ? (t / 1e4).toFixed(t % 1e4 > 500 && t % 1e4 < 9500 ? 1 : 0) + "万" : t >= 1e8 ? (t / 1e8).toFixed(t % 1e8 > 5e6 && t % 1e8 < 95e6 ? 1 : 0) + "亿" : t
}

export const styleObjectToString = (style : Record<string, string>) => {
	const list : string[] = []
	Object.keys(style).forEach(key => {
		list.push(`${key}:${style[key]}`)
	})
	return list.join(';')
}